<!--长效养护-->
<template>
  <page-meta
    :page-font-size="baseFontSize + 'rpx'"
    :root-font-size="baseFontSize + 'rpx'"
  ></page-meta>
  <view class="u-page flex flex-direction">
    <view class="addr flex align-center">
      <view>当前位置</view>
      <view class="location flex-sub text-right"
        >{{ latitude || '未获取' }}, {{ longitude || '未获取' }}</view
      >
      <view @click="startLocation()" class="refresh">刷新</view>
    </view>
    <scroll-view scroll-y class="form flex-sub main">
      <view class="section">
        <image src="/static/images/base.png" mode="widthFix"></image>
        <text>基础信息</text>
      </view>
      <uni-forms :modelValue="formData" border label-width="16rem">
        <uni-forms-item label="设施名称" name="facilityName">{{
          facilityName
        }}</uni-forms-item>
        <uni-forms-item label="所属部位" name="placeName">
          <!-- <uni-data-picker
						placeholder="请选择所属部位"
						popup-title="请选择所属部位"
						:placeholderStyle="placeholderStyle"
						:localdata="dataTree"
						v-model="classes"
						:border="false"
						@change="onchange"
						@nodeclick="onnodeclick"
						@popupopened="onpopupopened"
						@popupclosed="onpopupclosed"
					></uni-data-picker> -->
          {{ placeName }}
        </uni-forms-item>
        <uni-forms-item label="所属构件" name="compName">
          {{ compName }}
          <!-- <uni-data-picker
						placeholder="请选择所属构件"
						popup-title="请选择所属构件"
						:placeholderStyle="placeholderStyle"
						:localdata="dataTree"
						v-model="classes"
						:border="false"
						@change="onchange"
						@nodeclick="onnodeclick"
						@popupopened="onpopupopened"
						@popupclosed="onpopupclosed"
					></uni-data-picker> -->
        </uni-forms-item>
        <uni-forms-item label="任务描述" name="name"
          ><uni-easyinput
            :inputBorder="false"
            type="text"
            v-model="taskContent"
            placeholder="请输入任务描述"
        /></uni-forms-item>

        <uni-forms-item label="上传照片" name="name" :required="true">
          <view class="container">
            <view class="preview-box">
              <view class="preview-list">
                <view class="preview-item" v-for="(item, index) in fileList" :key="index">
                  <image style="width: 120upx; height: 120upx" :src="item"></image>
                  <uni-icons
                    class="delete-icon"
                    @click="removeImg(index)"
                    type="closeempty"
                    size="10"
                  ></uni-icons>
                </view>
                <view class="upload-btn-area"
                  ><image
                    v-if="fileList.length < 9"
                    @click="chooseImage"
                    src="/static/images/upload.png"
                    mode="widthFix"
                  ></image
                ></view>
              </view>
            </view>
          </view>
        </uni-forms-item>

        <uni-forms-item label="上报内容" :required="true"
          ><uni-easyinput
            type="textarea"
            :inputBorder="false"
            v-model="reportContent"
            placeholder="请输入上报内容"
        /></uni-forms-item>
      </uni-forms>
    </scroll-view>
    <view class="page-footer">
      <button
        @click="submitReport"
        class="save-btn cu-btn block bg-blue lg"
        :disabled="isSubmiting"
        type="blue"
      >
        <uni-icons type="spinner-cycle" size="20" v-if="isSubmiting"></uni-icons>
        提交
      </button>
    </view>
  </view>
</template>

<script>
import upload from '@/components/upload.vue';
import { reportChangXiaoApi } from '@/api/system/changxiao.js';
export default {
  components: {
    upload
  },
  data() {
    return {
      dataTree: null,
      formData: {},
      placeholderStyle: {
        fontSize: '14px'
      },
      latitude: '',
      longitude: '',
      detailId: '',
      detailObj: {},
      projectName: '',
      facilityName: '',
      compName: '',
      componentId: '',
      placeName: '',
      taskContent: '',
      reportContent: '',
      fileList: [],
      isSubmiting: false
    };
  },
  computed: {
    baseFontSize() {
      return this.$store.getters.fontSize;
    }
  },
  onLoad(e) {
    console.log(e);
    if (e && e.id) {
      this.detailId = e.id;
      this.projectName = e.projectName;
      this.facilityName = e.facilityName;
      this.placeName = e.placeName;
      this.compName = e.compName;
      this.componentId = e.componentId;
    }
  },
  mounted() {
    this.startLocation();
  },
  methods: {
    startLocation() {
      let _this = this;
      uni.startLocationUpdate({
        success: (res) => {
          //成功的逻辑
          uni.onLocationChange((data) => {
            this.latitude = data.latitude.toFixed(6);
            this.longitude = data.longitude.toFixed(6);
          });
        },
        fail: (err) => {
          console.log(err);
          //失败的逻辑
          //1.wx.showModal引导用户授权
          //2.通过wx.openSetting让用户开启权限
          uni.showModal({
            //引导用户授权
            title: '提示',
            content: '请打开定位权限',
            confirmText: '设置',
            cancelText: '取消',
            showCancel: false,
            success: (res) => {
              //点击“确认”时打开设置页面
              if (res.confirm) {
                uni.openSetting({
                  //打开设置页面让用户选择权限
                  success: (res) => {
                    console.log(res);
                    if (res.authSetting['scope.userLocation'] == true) {
                      uni.onLocationChange((data) => {
                        //实时获取用户最新的经纬度信息
                        console.log(data);
                      });
                    }
                  }
                });
              } else {
                //取消打开设置授权页面
                uni.showToast({
                  title: '取消授权',
                  icon: 'none'
                });
              }
            }
          });
        }
      });
    },
    removeImg(index) {
      this.fileList.splice(index, 1);
    },
    submitReport() {
      if (this.isSubmiting) {
        return;
      }
      if (this.fileList.length == 0) {
        uni.showToast({
          title: '请上传图片',
          icon: 'error',
          duration: 2000
        });
        return;
      }
      if (!this.reportContent) {
        uni.showToast({
          title: '请填写上报内容',
          icon: 'error',
          duration: 2000
        });
        return;
      }
      this.isSubmiting = true;
      reportChangXiaoApi({
        taskId: this.detailId, // id
        latitude: this.latitude, // 坐标
        longitude: this.longitude, // 坐标
        projectName: this.projectName, // 设备名
        facilityName: this.facilityName, // 所属部位
        placeName: this.placeName, // 所属部位
        compName: this.compName, // 所属构建
        componentId: this.componentId, // 所属构建
        taskContent: this.taskContent, // 任务描述
        images: this.fileList, // 图片最多9个
        reportContent: this.reportContent // 上报内容
      })
        .then((res) => {
          uni.showToast({
            title: '操作成功',
            icon: 'success',
            duration: 2000
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1000);
        })
        .finally(() => {
          this.isSubmiting = false;
        });
    },
    chooseImage() {
      uni.chooseImage({
        count: 9,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths;
          this.uploadImage(tempFilePaths);
        }
      });
    },
    uploadImage(images) {
      const count = images.length;
      let currentIndex = 0;
      for (let i = 0; i < count; i++) {
        uni.uploadFile({
          url: 'https://ruoyi.51wephone.cn/admin-api/infra/file/upload', //上传接口地址
          filePath: images[i],
          name: 'file',
          formData: {},
          header: {
            Authorization: `Bearer ${uni.getStorageSync('ACCESS_TOKEN')}`
          },
          success: (res) => {
            currentIndex++;
            const data = JSON.parse(res.data);
            if (currentIndex >= count) {
              uni.showToast({
                title: '上传成功',
                icon: 'success',
                duration: 2000
              });
            }
            this.fileList.push(JSON.parse(res.data).data);
          }
        });
      }
    }
  }
};
</script>
<style lang="scss">
page {
  height: 100%;
}
</style>
<style lang="scss" scoped>
@import '@/static/scss/form.scss';

.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.upload-box {
  margin-bottom: 20px;
}

.preview-box {
  flex: 1;
}

.preview-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: center;

  .upload-btn-area {
    width: 120upx;
    height: 120upx;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1upx dashed #f2f2f2;
    border-radius: 12upx;
    box-sizing: border-box;
    display: flex;
    justify-content: center;
    align-items: center;

    :deep(.uni-icons) {
      font-size: 80upx !important;
    }
  }
}

.preview-item {
  box-sizing: border-box;
  width: 120upx;
  height: 120upx;
  margin-right: 10px;
  margin-bottom: 10px;
  position: relative;

  .delete-icon {
    position: absolute;
    right: -8upx;
    top: -8upx;
    background: rgba(0, 0, 0, 0.2);
    border-radius: 50%;
    padding: 8upx;

    .uni-icons {
      font-size: 30upx !important;
    }
  }
}

.preview-item image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
